<script>
$(document).ready(function(){
	$userApiKey = ""
	$username = ""
	$("#submit").click(function(e){
		e.preventDefault();
		var submitBTN = $(this)
		submitBTN.attr('disabled', 'disabled')
		username = $("#username").val()
		var password = $("#password").val()
		var encodedString = btoa(username + ":" + password)
		var endPoint = "http://127.0.0.1:8000/api/v1/login/?format=json"
		$.ajax({
			type: "GET",
			url: endPoint,
			data: {},
			success: function(data){
				userApiKey = data.objects[0].api_key
				$.mobile.navigate("#listPage")
			},
			error: function(data){
		
			},
			beforeSend: function(xhr){
				xhr.setRequestHeader("Authorization", "Basic " + encodedString)
			},
			complete: function(){
				submitBTN.prop("disabled", false)
			}
		})
	});
	$("#newRecod").click(function(e){
		e.preventDefault();
		var newApiString = username + ":" + userApiKey
		console.log(newApiString)
		var endPoint = "http://127.0.0.1:8000/api/v1/posting/"
		var data = JSON.stringify({
			"post": $("#postText").val(),
		})
		$.ajax({
			type: "POST",
			url: endPoint,
			data: data,
			contentType: "application/json",
			success: function(data){
				console.log(data);
			},
			error: function(data){
				console.log(data);
			},
			beforeSend: function(xhr){
				xhr.setRequestHeader("Authorization", "ApiKey " + newApiString)
			},
			complete: function(data){
				console.log(data);
			}
		})
	});
	function getPostingData(listId){
		var newApiString = username + ":" + userApiKey
		var endPoint = "http://127.0.0.1:8000/api/v1/posting/"
		var data = JSON.stringify({
			"limit": 400,
		})
		$.ajax({
			type: "GET",
			url: endPoint,
			data: data,
			contentType: "application/json",
			success: function(data){
				var objectArray = data.objects;
				console.log(objectArray)
				$.each(objectArray, function(){
					var listItemSingle = $(this);
					console.log(listItemSingle)
					$(listId).append("<li class=\"ui-li-static ui-body-inherit\">" + listItemSingle[0].post  + "</li>");
				})
			},
			error: function(data){
				console.log(data);
			},
			beforeSend: function(xhr){
				xhr.setRequestHeader("Authorization", "ApiKey " + newApiString)
			},
			complete: function(data){
				console.log(data);
			}
		})
	}
	$(window).on("navigate", function(event) {
			var pageId = $.mobile.activePage.attr("id");
			if (pageId == "two"){
				console.log(userApiKey);
				$("#" + pageId + " .ui-content").html("<form id='postForm'><input type='text' id='postText' /></form>")
			} else if(pageId == "listPage") {
				getPostingData("#theListPostings")
			}
	});
});
</script>